import { RouteObject } from "react-router-dom";
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  UploadOutlined,
  UserOutlined,
  VideoCameraOutlined,
  SettingOutlined
} from '@ant-design/icons';

import Login from "@/pages/login/index";
import BasicLayout from "@/components/layout/basic-layout";
import EmptyLayout from "@/components/layout/empty-layout";
import Setting from "./pages/setting";
import Testing from "./pages/testing";
import Error404 from "@/pages/error/e404";

import type { MenuProps } from 'antd';

type IMenuItem = Required<MenuProps>['items'][number];

type IRouterItemConfig = {
  path: string;
  Component: React.ComponentType;
  children?: IRouterItemConfig[];
  menuInfo?: {
    label: string;
    key: string;
    icon:  React.ReactNode;
  };
  [key: string]: any;
};

const routeConfig: IRouterItemConfig[] = [
  {
    path: "/login",
    Component: Login,
  },
  {
    path: "/",
    Component: BasicLayout,
    tag: "menuRoot",
    // 添加一个重定向，确保未登录时重定向到登录页面
    // loader: () => {
    //   if (!isLoggedIn()) {
    //     return redirect("/login");
    //   }
    // },

    children: [
      {
        path: "system",
        Component: EmptyLayout,
        menuInfo: {
          label: "系统",
          key: 'system',
          icon: <SettingOutlined />
        },
        children: [
          {
            path: "setting",
            Component: Setting,
            menuInfo: {
              label: "设置",
              key: 'setting',
              icon: null
            },
           
          }
        ]
      },
      {
        path: "testing",
        Component: Testing,
        menuInfo: {
          label: "测试",
          key: 'testing',
          icon: <SettingOutlined />
        }
      },
    ],
  },

  {
    path: "*", // 通配符路由，匹配所有未定义的路径
    Component: Error404,
  },
];




export const getReactRouterConfig = (cfg:IRouterItemConfig[] ): RouteObject[] => {

  const result: RouteObject[] = [];

  cfg.forEach((item) => {
    const { menuInfo, ...rest } = item
    const route: RouteObject = rest

    if (item.children) {
      route.children = getReactRouterConfig(item.children);
    }
    result.push(route);
  });

  return result;

}

const getAntdMenuFromRoot = (cfg:IRouterItemConfig[] ): IMenuItem[] => {

  const result: IMenuItem[] = [];

  cfg.forEach((item) => {
    const { menuInfo } = item

    if (menuInfo) {
      const menuItem: any = menuInfo 

      const { path: p, children} = item

      if (children) {
        menuItem.children = getAntdMenuFromRoot(children, );
      }
      result.push(menuItem);
    }
  });

  return result;

}


export const getAntdMenuConfig = (cfg:IRouterItemConfig[] ): IMenuItem[] => {

  const menuRoot = cfg.find((item) => item.tag === "menuRoot");

  if (menuRoot) {
    return getAntdMenuFromRoot(menuRoot.children || [] )
  }

  return []

}



export const routes = getReactRouterConfig(routeConfig)

export const menuItems = getAntdMenuConfig(routeConfig)